package com.algebra.activiti.service.impl;

import com.algebra.activiti.service.ActivitiService;
import com.algebra.activiti.service.ActivitiVariableService;
import com.algebra.activiti.util.common.BusinessTaskUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author al
 * @date 2020/10/22 10:59
 * @description
 */
@Service
@Slf4j
public class ActivitiServiceImpl implements ActivitiService {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngineConfigurationImpl processEngineConfiguration;

    /**
     * 启动流程
     */
    @Override
    public void startProcesses(String id, String businessKey) {
        //流程图id，业务表id
        ProcessInstance pi = runtimeService.startProcessInstanceByKey(id, businessKey);
        log.info("流程启动成功，流程id:" + pi.getId());
    }

    /**
     * <p>描述: 根据用户id查询待办任务列表</p>
     *
     * @author 范相如
     * @date 2018年2月25日
     */
    @Override
    public List<Task> findTasksByUserId(String userId) {
        List<Task> resultTask = taskService.createTaskQuery().processDefinitionKey("process").taskCandidateOrAssigned(userId).list();
        return resultTask;
    }

    @Override
    public Task findTaskById(String taskId) {
        List<Task> resultTask = taskService.createTaskQuery().taskId(taskId).list();
        if (resultTask != null) {
            return resultTask.get(0);
        }
        return null;
    }

    /**
     * <p>描述:任务审批     （通过/拒接） </p>
     *
     * @param taskId 任务id
     * @param userId 用户id
     * @param result false OR true
     * @author 范相如
     * @date 2018年2月25日
     */
    @Override
    public void completeTask(String taskId, String userId, String result) {
        //获取流程实例
        taskService.claim(taskId, userId);
        //获取任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //获取流程实例ID
        String proInsId = task.getProcessInstanceId();
        //获取流程实例
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(proInsId).singleResult();
        //获取业务外键
        String businessKey = process.getBusinessKey();
        String[] array = businessKey.split(":");
        String businessId = array[1];
        //业务处理
        try {
            Class clazz = BusinessTaskUtil.class;
            Object obj = clazz.newInstance();
            Method method = clazz.getMethod("actBusiness_" + task.getFormKey(), String.class, String.class, String.class);
            method.invoke(obj, userId, businessId, result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行业务方法错误！");

        }
        taskService.complete(taskId);
    }

    /**
     * 更改业务流程状态#{ActivityDemoServiceImpl.updateBizStatus(execution,"tj")}
     *
     * @param execution
     * @param status
     */
    @Override
    public void updateBizStatus(DelegateExecution execution, String status) {
        String bizId = execution.getProcessInstanceBusinessKey();
        //根据业务id自行处理业务表
        log.info("业务表[" + bizId + "]状态更改成功，状态更改为：" + status);
    }


    //流程节点权限用户列表${ActivityDemoServiceImpl.findUsers(execution,sign)}
    @Override
    public List<String> findUsersForSL(DelegateExecution execution) {
        return Arrays.asList("sly1", "sly2");
    }

    //流程节点权限用户列表${ActivityDemoServiceImpl.findUsers(execution,sign)}
    @Override
    public List<String> findUsersForSP(DelegateExecution execution) {
        return Arrays.asList("spy1", "uspy2");
    }


}
